import { Injectable } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { ToolsService } from 'src/utils/tools.service';
import { Repository, DataSource } from 'typeorm';
import { AccountEntity } from '../account/entities/account.entity';
import { DepartmentEntity } from '../department/entities/department.entity';
import { RoleEntity } from '../role/entities/role.entity';
import { AddRoleDto } from './dto/add-role.dto';
import { CreateUserDto } from './dto/create-user.dto';
import { JoinDepartmentDto } from './dto/join-department.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UsersEntity } from './entities/user.entity';

@Injectable()
export class UserService {
  @InjectRepository(UsersEntity)
  private readonly usersRepository: Repository<UsersEntity>;
  @InjectRepository(AccountEntity)
  private readonly accountRepository: Repository<AccountEntity>;
  @InjectRepository(DepartmentEntity)
  private readonly departmentRepository: Repository<DepartmentEntity>;
  @InjectDataSource()
  private readonly dataSource: DataSource;
  async create(createUserDto: CreateUserDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务保存到副表
      const account = await manager
        .getRepository(AccountEntity)
        .createQueryBuilder('account')
        .where('account.accountnumer = :accountnumer', {
          accountnumer: createUserDto.accountnumer,
        })
        .leftJoinAndSelect('account.user', 'user')
        .select(['account', 'user'])
        .addSelect('user.password')
        .getOne();
      if (account) {
        throw new Error('账号已存在');
      } else {
        const user = new UsersEntity();
        const account = new AccountEntity();
        account.accountnumer = createUserDto.accountnumer;
        await manager.save(account);
        user.username = createUserDto.accountnumer;
        user.password = createUserDto.password;
        user.account = account;
        await manager.save(user);
        return user;
      }
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async findAll(username: string) {
    try {
      const res = await this.usersRepository
        .createQueryBuilder('user')
        .where('user.username LIKE :param and user.username != :username', {
          username: 'admin',
        })
        .setParameters({
          param: '%' + username + '%',
        })
        .orderBy('user.id', 'ASC')
        .leftJoinAndSelect('user.department', 'department')
        .leftJoinAndSelect('user.roles', 'roles')
        .select(['user', 'department.departmentname', 'roles'])
        .getManyAndCount();
      return res;
    } catch (error) {
      ToolsService.fail(error);
    }
    // await this.usersRepository.findAndCount({
    //   select: ["username"],
    //   relations: ['department'],
    // })
  }

  async findOne(id: string) {
    return await this.usersRepository.findOne({
      where: {
        id,
      },
    });
  }

  async update(id: string, updateUserDto: UpdateUserDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务
      const user = await manager
        .getRepository(UsersEntity)
        .createQueryBuilder('user')
        .where('user.id = :id', {
          id: id,
        })
        .getOne();

      if (!user) {
        throw new Error('用户不存在');
      }
      user.username = updateUserDto.username;
      user.password = updateUserDto.password;
      user.headPicture = updateUserDto.headPicture;
      await manager.save(user);
      return user;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async remove(id: string, user) {
    // 获取连接并创建新的queryRunner
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      if (id == user.userid) {
        ToolsService.fail('违规操作');
      }
      const manager = await queryRunner.manager; //使用事务保存到副表
      const userRepository = manager.getRepository(UsersEntity);
      const userEntity = await userRepository
        .createQueryBuilder('user')
        .leftJoinAndSelect('user.account', 'account')
        .where('user.id = :id', { id: id })
        .getOne();
      const accountRepository = manager.getRepository(AccountEntity);
      if (userEntity.account && userEntity.account.id) {
        await accountRepository
          .createQueryBuilder('account')
          .delete()
          .where('account.id = :id', { id: userEntity.account.id })
          .execute();
      } else {
        ToolsService.fail('账号不存在');
      }
      return userEntity;
    } catch (error) {
      console.log('删除，取消事务');
      ToolsService.fail(error);
    }
  }

  async addRole(addRoleDto: AddRoleDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务
      // const user = await this.usersRepository.findOne({
      //   id: addRoleDto.userId,
      // });
      const user = await manager
        .getRepository(UsersEntity)
        .createQueryBuilder('user')
        .where('user.id = :id', {
          id: addRoleDto.userId,
        })
        .getOne();

      if (!user) {
        throw new Error('用户不存在');
      }

      if (addRoleDto.roleIds.length > 0) {
        const roles = [];
        for (let i = 0; i < addRoleDto.roleIds.length; i++) {
          const listOne = await manager
            .getRepository(RoleEntity)
            .createQueryBuilder('role')
            .where('role.id = :id', { id: addRoleDto.roleIds[i] })
            .getOne();
          if (!listOne) ToolsService.fail('角色id不存在');
          roles.push(listOne);
        }
        const userEntity = new UsersEntity();
        userEntity.id = addRoleDto.userId;
        userEntity.roles = roles;
        await manager.save(userEntity);
        return '添加成功';
      } else {
        const userEntity = new UsersEntity();
        userEntity.id = addRoleDto.userId;
        userEntity.roles = [];
        await manager.save(userEntity);
        return '添加成功';
      }
    } catch (error) {
      console.log('删除，取消事务');
      ToolsService.fail(error);
    }
  }

  async findOwnerRoles(userId: string) {
    try {
      const user = await this.usersRepository
        .createQueryBuilder('user')
        .where('user.id = :id', { id: userId })
        .leftJoinAndSelect('user.roles', 'roles')
        .select(['user', 'roles'])
        .getOneOrFail();
      return user.roles;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async findOwnerDepartment(userId: string) {
    try {
      const user = await this.usersRepository
        .createQueryBuilder('user')
        .where('user.id = :id', { id: userId })
        .leftJoinAndSelect('user.department', 'department')
        .select(['user', 'department'])
        .getOneOrFail();
      return user.department;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async joinDepartment(joinDepartmentDto: JoinDepartmentDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务

      const user = await manager
        .getRepository(UsersEntity)
        .createQueryBuilder('user')
        .where('user.id = :id', {
          id: joinDepartmentDto.userId,
        })
        .getOne();

      const department = await manager
        .getRepository(DepartmentEntity)
        .createQueryBuilder('department')
        .where('department.id = :id', {
          id: joinDepartmentDto.departmentId,
        })
        .getOne();

      if (!user) {
        throw new Error('用户不存在');
      }
      user.department = department;
      await manager.save(user);
    } catch (error) {
      console.log('删除，取消事务');
      ToolsService.fail(error);
    }
  }
}
